package io.renren.modules.erp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.constants.BusinessConstants;
import io.renren.common.exception.JshException;
import io.renren.common.utils.DateTimeUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.RandomString;
import io.renren.common.utils.StringUtil;
import io.renren.modules.erp.dao.AccountHeadMapper;
import io.renren.modules.erp.dao.DepotHeadMapper;
import io.renren.modules.erp.dao.DepotHeadMapperEx;
import io.renren.modules.erp.dao.DepotItemMapperEx;
import io.renren.modules.erp.entity.*;
import io.renren.modules.erp.service.AccountHeadService;
import io.renren.modules.erp.service.DepotHeadService;
import io.renren.modules.erp.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.stream.Collectors;

import static io.renren.common.utils.Tools.getCenternTime;
@Service("depotHeadService")
public class DepotHeadServiceImpl extends ServiceImpl<DepotHeadMapper, DepotHead> implements DepotHeadService {
    private Logger logger = LoggerFactory.getLogger(DepotHeadServiceImpl.class);

    @Autowired
    private DepotHeadMapper depotHeadMapper;
    @Autowired
    private AccountHeadMapper accountHeadMapper;

    @Autowired
    private DepotHeadMapperEx depotHeadMapperEx;

    @Autowired
    DepotItemServiceImpl depotItemService;
    @Autowired
    private SupplierServiceImpl supplierService;
    @Autowired
    private SerialNumberServiceImpl serialNumberService;
    @Autowired
    private OrgaUserRelServiceImpl orgaUserRelService;
    @Autowired
    DepotItemMapperEx depotItemMapperEx;

    @Autowired
    private AccountHeadService accountHeadService;
//    @Autowired
//    private LogService logService;

    public DepotHead getDepotHead(long id)throws Exception {
        DepotHead result=null;
        try{
            result=depotHeadMapper.selectByPrimaryKey(id);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    public List<DepotHead> getDepotHead()throws Exception {
        DepotHeadExample example = new DepotHeadExample();
        example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<DepotHead> list=null;
        try{
            list=depotHeadMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public PageUtils select(String type, String subType, String roleType, String number, String beginTime, String endTime,
                            String materialParam, String depotIds, int currPage, int pageSize,Long userId,String payType,String status,String transportType,String serviceType,String userName,String deliverDate,String billType,String salesDate,String stockType,String deliveryType,String deliveryBillNo,String salesBillNo,String externalNumber,String buyer,String purchaseStockBillNo,String purchaseSalesBillNo,String organName,String accountSalesBillno)throws Exception {
        List<DepotHeadVo4List> resList = new ArrayList<DepotHeadVo4List>();

        Page<DepotHeadVo4List> page = new Page<>(currPage,pageSize);
        try{
            String [] creatorArray = getCreatorArray(roleType,userId);
            page.setRecords(depotHeadMapperEx.selectByConditionDepotHead(type, subType, creatorArray, number, beginTime, endTime, materialParam, depotIds, page,payType,status,transportType,serviceType,userName,deliverDate,billType,salesDate,stockType,deliveryType,deliveryBillNo,salesBillNo,externalNumber,buyer,purchaseStockBillNo,purchaseSalesBillNo,organName,accountSalesBillno));
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        if (null != page.getRecords()) {
            for (DepotHeadVo4List dh : page.getRecords()) {
                if(dh.getAccountIdList() != null) {
                    String accountidlistStr = dh.getAccountIdList().replace("[", "").replace("]", "").replaceAll("\"", "");
                    dh.setAccountIdList(accountidlistStr);
                               }
                if(dh.getAccountMoneyList() != null) {
                    String accountmoneylistStr = dh.getAccountMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
                    dh.setAccountMoneyList(accountmoneylistStr);
                }
                if(dh.getOtherMoneyList() != null) {
                    String otherMoneyListStr = dh.getOtherMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
                    dh.setOtherMoneyList(otherMoneyListStr);
                }
                if(dh.getChangeAmount() != null) {
                    dh.setChangeAmount(dh.getChangeAmount().abs());
                }
                if(dh.getTotalPrice() != null) {
                    dh.setTotalPrice(dh.getTotalPrice().abs());
                }
                if(dh.getOperTime() != null) {
                    dh.setOperTimeStr(dh.getOperTime());
                }
                dh.setMaterialsList(findMaterialsListByHeaderId(dh.getId()));
                resList.add(dh);
            }
        }
        return new PageUtils(page);
    }

    //调拨单
    public PageUtils getTransferList(String type, String subType, String roleType, String number, String beginTime, String endTime,
                            String materialParam, String depotIds, int currPage, int pageSize,Long userId,String status)throws Exception {
        List<DepotHeadVo4List> resList = new ArrayList<DepotHeadVo4List>();

        Page<DepotHeadVo4List> page = new Page<>(currPage,pageSize);
        try{
            String [] creatorArray = getCreatorArray(roleType,userId);
            page.setRecords(depotHeadMapperEx.selectByTransferList(type, subType, creatorArray, number, beginTime, endTime, materialParam, depotIds, page,status));
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        if (null != page.getRecords()) {
            for (DepotHeadVo4List dh : page.getRecords()) {
                if(dh.getAccountIdList() != null) {
                    String accountidlistStr = dh.getAccountIdList().replace("[", "").replace("]", "").replaceAll("\"", "");
                    dh.setAccountIdList(accountidlistStr);
                }
                if(dh.getAccountMoneyList() != null) {
                    String accountmoneylistStr = dh.getAccountMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
                    dh.setAccountMoneyList(accountmoneylistStr);
                }
                if(dh.getOtherMoneyList() != null) {
                    String otherMoneyListStr = dh.getOtherMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
                    dh.setOtherMoneyList(otherMoneyListStr);
                }
                if(dh.getChangeAmount() != null) {
                    dh.setChangeAmount(dh.getChangeAmount().abs());
                }
                if(dh.getTotalPrice() != null) {
                    dh.setTotalPrice(dh.getTotalPrice().abs());
                }
                if(dh.getOperTime() != null) {
                    dh.setOperTimeStr(dh.getOperTime());
                }
                dh.setMaterialsList(findMaterialsListByHeaderId(dh.getId()));
                resList.add(dh);
            }
        }
        return new PageUtils(page);
    }


    //盘点单
    public PageUtils getCheckList(String type, String subType, String roleType, String number, String beginTime, String endTime,
                                     String materialParam, String depotIds, int currPage, int pageSize,Long userId,String status,String checkStatus,String depotId)throws Exception {
        List<DepotHeadVo4List> resList = new ArrayList<DepotHeadVo4List>();


        Page<DepotHeadVo4List> page = new Page<>(currPage,pageSize);
        try{
            String [] creatorArray = getCreatorArray(roleType,userId);
            page.setRecords(depotHeadMapperEx.getCheckList(type, subType, creatorArray, number, beginTime, endTime, materialParam, depotIds, page,status,checkStatus,depotId));
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        if (null != page.getRecords()) {
            for (DepotHeadVo4List dh : page.getRecords()) {
                if(dh.getAccountIdList() != null) {
                    String accountidlistStr = dh.getAccountIdList().replace("[", "").replace("]", "").replaceAll("\"", "");
                    dh.setAccountIdList(accountidlistStr);
                }
                if(dh.getAccountMoneyList() != null) {
                    String accountmoneylistStr = dh.getAccountMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
                    dh.setAccountMoneyList(accountmoneylistStr);
                }
                if(dh.getOtherMoneyList() != null) {
                    String otherMoneyListStr = dh.getOtherMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
                    dh.setOtherMoneyList(otherMoneyListStr);
                }
                if(dh.getChangeAmount() != null) {
                    dh.setChangeAmount(dh.getChangeAmount().abs());
                }
                if(dh.getTotalPrice() != null) {
                    dh.setTotalPrice(dh.getTotalPrice().abs());
                }
                if(dh.getOperTime() != null) {
                    dh.setOperTimeStr(dh.getOperTime());
                }
                dh.setMaterialsList(findMaterialsListByHeaderId(dh.getId()));
                resList.add(dh);
            }
        }
        return new PageUtils(page);
    }












    public PageUtils select2(String type, String subType, String roleType, String number, String beginTime, String endTime,
                            String materialParam, String depotIds, int currPage, int pageSize,Long userId,String payType,String status,String transportType,String serviceType,String userName,String deliverDate,String billType,String salesDate,String stockType,String deliveryType,String deliveryBillNo,String salesBillNo,String externalNumber,String organName)throws Exception {
        List<DepotHeadVo4List> resList = new ArrayList<DepotHeadVo4List>();

        Page<DepotHeadVo4List> page = new Page<>(currPage,pageSize);
        try{
            String [] creatorArray = getCreatorArray(roleType,userId);
            page.setRecords(depotHeadMapperEx.selectByConditionDepotHead2(type, subType, creatorArray, number, beginTime, endTime, materialParam, depotIds, page,payType,status,transportType,serviceType,userName,deliverDate,billType,salesDate,stockType,deliveryType,deliveryBillNo,salesBillNo,externalNumber,organName));
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        if (null != page.getRecords()) {
            for (DepotHeadVo4List dh : page.getRecords()) {
                if(dh.getAccountIdList() != null) {
                    String accountidlistStr = dh.getAccountIdList().replace("[", "").replace("]", "").replaceAll("\"", "");
                    dh.setAccountIdList(accountidlistStr);
                }
                if(dh.getAccountMoneyList() != null) {
                    String accountmoneylistStr = dh.getAccountMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
                    dh.setAccountMoneyList(accountmoneylistStr);
                }
                if(dh.getOtherMoneyList() != null) {
                    String otherMoneyListStr = dh.getOtherMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
                    dh.setOtherMoneyList(otherMoneyListStr);
                }
                if(dh.getChangeAmount() != null) {
                    dh.setChangeAmount(dh.getChangeAmount().abs());
                }
                if(dh.getTotalPrice() != null) {
                    dh.setTotalPrice(dh.getTotalPrice().abs());
                }
                if(dh.getOperTime() != null) {
                    dh.setOperTimeStr(dh.getOperTime());
                }
                dh.setMaterialsList(findMaterialsListByHeaderId(dh.getId()));
                resList.add(dh);
            }
        }
        return new PageUtils(page);
    }


    public Long countDepotHead(String type, String subType, String roleType,String number, String beginTime, String endTime,
                               String materialParam, String depotIds,Long userId) throws Exception{
        Long result=null;
        try{
            String [] creatorArray = getCreatorArray(roleType, userId);
            result=depotHeadMapperEx.countsByDepotHead(type, subType, creatorArray, number, beginTime, endTime, materialParam, depotIds);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    /**
     * 根据角色类型获取操作员数组
     * @param roleType
     * @return
     * @throws Exception
     */
    public String[] getCreatorArray(String roleType,Long userId) throws Exception {
        String creator = getCreatorByRoleType(roleType,userId);
        String [] creatorArray=null;
        if(StringUtil.isNotEmpty(creator)){
            creatorArray = creator.split(",");
        }
        return creatorArray;
    }

    /**
     * 根据角色类型获取操作员
     * @param roleType
     * @return
     * @throws Exception
     */
    public String getCreatorByRoleType(String roleType,Long userId) throws Exception {
        String creator = "";
        if(BusinessConstants.ROLE_TYPE_PRIVATE.equals(roleType)) {
            creator = userId.toString();
        } else if(BusinessConstants.ROLE_TYPE_THIS_ORG.equals(roleType)) {
            creator = orgaUserRelService.getUserIdListByUserId(userId);
        }
        return creator;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertDepotHead(String beanJson, HttpServletRequest request)throws Exception {
        DepotHead depotHead = JSONObject.parseObject(beanJson, DepotHead.class);
//        depotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
        depotHead.setStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
        int result=0;
        try{
            result=depotHeadMapper.insert(depotHead);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }





    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updateDepotHead(String beanJson, Long id, HttpServletRequest request) throws Exception{
        DepotHead dh=null;
        try{
            dh = depotHeadMapper.selectByPrimaryKey(id);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        DepotHead depotHead = JSONObject.parseObject(beanJson, DepotHead.class);
        depotHead.setId(id);
        depotHead.setStatus(dh.getStatus());
        depotHead.setCreateTime(dh.getCreateTime());
        int result=0;
        try{
            result = depotHeadMapper.updateByPrimaryKey(depotHead);

        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int deleteDepotHead(Long id, HttpServletRequest request)throws Exception {
        int result=0;
        try{
            result = depotHeadMapper.deleteByPrimaryKey(id);

        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteDepotHead(String ids, HttpServletRequest request)throws Exception {
        List<Long> idList = StringUtil.strToLongList(ids);
        DepotHeadExample example = new DepotHeadExample();
        example.createCriteria().andIdIn(idList);
        int result=0;
        try{
            result = depotHeadMapper.deleteByExample(example);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    public int checkIsNameExist(Long id, String name)throws Exception {
        DepotHeadExample example = new DepotHeadExample();
        example.createCriteria().andIdNotEqualTo(id).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<DepotHead> list = null;
        try{
            list = depotHeadMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list==null?0:list.size();
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchSetStatus(String status, String depotHeadIDs,String type)throws Exception {
        List<Long> ids = StringUtil.strToLongList(depotHeadIDs);
        DepotHead depotHead = new DepotHead();
        depotHead.setStatus(status);
        DepotHeadExample example = new DepotHeadExample();
        example.createCriteria().andIdIn(ids);
        int result = 0;
        try{
            result = depotHeadMapper.updateByExampleSelective(depotHead, example);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        List<DepotHead> listDepot= depotHeadMapper.selectList(new QueryWrapper<DepotHead>().in("id",ids));

        //销售销货单 审核生成应收帐   反审核删除对应应收帐
        if(type.equals("销货")&&status.equals("1")){
            List<AccountHead> accountHeadList  = new ArrayList<>();
            List<AccountHead> collect = listDepot.stream().map(item -> {
                AccountHead accountHead=new AccountHead();
                accountHead.setBillNo("YSZ"+ DateTimeUtils.getCurrentDateString().substring(2,6)+ RandomString.getSixRandomString());
                accountHead.setType("应收账");
                accountHead.setBillTime(new Date());
                accountHead.setOrganId(item.getOrganId());
                accountHead.setSourceType("销货单");
                accountHead.setUserName(item.getUserName());
                accountHead.setReceivablesBillno(item.getNumber());
                accountHead.setTotalPrice(item.getTotalPrice());
                accountHead.setIsverification(new BigDecimal(0));
                accountHead.setNoverification(item.getTotalPrice());
                accountHeadList.add(accountHead);
                return accountHead;
            }).collect(Collectors.toList());
            accountHeadService.saveBatch(accountHeadList);
        }else if(type.equals("销货")&&status.equals("0")){
            List<String> numbers = listDepot.stream().map(DepotHead::getNumber).collect(Collectors.toList());

            accountHeadMapper.delete(new QueryWrapper<AccountHead>().in("receivables_billno",numbers));
        }
        //采购进货单审核生成应付帐   反审核删除对应付帐
        if(type.equals("采购进货")&&status.equals("1")){
            List<AccountHead> accountHeadList  = new ArrayList<>();
            List<AccountHead> collect = listDepot.stream().map(item -> {
                AccountHead accountHead=new AccountHead();
                accountHead.setBillNo("YFZ"+ DateTimeUtils.getCurrentDateString().substring(2,6)+ RandomString.getSixRandomString());
                accountHead.setType("应付账");
                accountHead.setBillTime(new Date());
                accountHead.setOrganId(item.getOrganId());
                accountHead.setSourceType("采购进货单");
                accountHead.setUserName(item.getUserName());
//                accountHead.setReceivablesBillno(item.getNumber());
//                accountHead.setAccountpayBillno(item.getNumber());
                accountHead.setTotalPrice(item.getTotalPrice());
                accountHead.setIsverification(new BigDecimal(0));
                accountHead.setNoverification(item.getTotalPrice());
                accountHeadList.add(accountHead);
                return accountHead;
            }).collect(Collectors.toList());
            accountHeadService.saveBatch(accountHeadList);
        }else if(type.equals("采购进货")&&status.equals("0")){
            List<String> numbers = listDepot.stream().map(DepotHead::getNumber).collect(Collectors.toList());

            accountHeadMapper.delete(new QueryWrapper<AccountHead>().in("accountpay_billno",numbers));
        }



        return result;
    }


    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int checkSetStatus(String checkStatus,Long depotHeadID,String depotItemIds)throws Exception {
        DepotHead depotHead = new DepotHead();
        depotHead.setCheckStatus(checkStatus);

//        String ids= depotItemIds.replace("\"", "");
        String [] idArray=depotItemIds.split(",");

        depotHeadMapper.checkItemSetStatus(depotHead, idArray);
        int result = 0;
        try{
            result = depotHeadMapper.checkSetStatus(depotHead, depotHeadID);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    /**
     * 创建一个唯一的序列号
     * */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public String buildOnlyNumber()throws Exception{
        Long buildOnlyNumber=null;
        synchronized (this){
            try{
                depotHeadMapperEx.updateBuildOnlyNumber(); //编号+1
                buildOnlyNumber= depotHeadMapperEx.getBuildOnlyNumber(BusinessConstants.DEPOT_NUMBER_SEQ);
            }catch(Exception e){
                JshException.writeFail(logger, e);
            }
        }
        if(buildOnlyNumber<BusinessConstants.SEQ_TO_STRING_MIN_LENGTH){
            StringBuffer sb=new StringBuffer(buildOnlyNumber.toString());
            int len=BusinessConstants.SEQ_TO_STRING_MIN_LENGTH.toString().length()-sb.length();
            for(int i=0;i<len;i++){
                sb.insert(0,BusinessConstants.SEQ_TO_STRING_LESS_INSERT);
            }
            return sb.toString();
        }else{
            return buildOnlyNumber.toString();
        }
    }

    public String findMaterialsListByHeaderId(Long id)throws Exception {
        String result = null;
        try{
            result = depotHeadMapperEx.findMaterialsListByHeaderId(id);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    public PageUtils findByAll(String beginTime, String endTime, String type, Integer pid, String dids, Integer oId, Integer currPage, Integer pageSize) throws Exception{
        List<DepotHeadVo4InDetail> list = null;
        Page<DepotHeadVo4InDetail> page = new Page(currPage,pageSize);
        try{
            list =depotHeadMapperEx.findByAll(beginTime, endTime, type, pid, dids, oId, page);
        }catch(Exception e){
            JshException.readFail(logger, e);

        }
        page.setRecords(list);
        return new PageUtils(page);
    }

    public int findByAllCount(String beginTime, String endTime, String type, Integer pid, String dids, Integer oId) throws Exception{
        int result = 0;
        try{
            result =depotHeadMapperEx.findByAllCount(beginTime, endTime, type, pid, dids, oId);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    public PageUtils findInOutMaterialCount(String beginTime, String endTime, String type, Integer pid, String dids, Integer oId, Integer currPage, Integer pageSize)throws Exception {
        List<DepotHeadVo4InOutMCount> list = null;
        Page<DepotHeadVo4InOutMCount> page = new Page(currPage,pageSize);

        try{
            list =depotHeadMapperEx.findInOutMaterialCount(beginTime, endTime, type, pid, dids, oId, page);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        page.setRecords(list);
        return new PageUtils(page);
    }

    public int findInOutMaterialCountTotal(String beginTime, String endTime, String type, Integer pid, String dids, Integer oId)throws Exception {
        int result = 0;
        try{
            result =depotHeadMapperEx.findInOutMaterialCountTotal(beginTime, endTime, type, pid, dids, oId);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    public List<DepotHeadVo4StatementAccount> findStatementAccount(String beginTime, String endTime, Integer organId, String supType, Integer currPage,Integer pageSize)throws Exception {
        List<DepotHeadVo4StatementAccount> list = null;
        Page<DepotHeadVo4StatementAccount> page = new Page(currPage,pageSize);

        try{
            list =depotHeadMapperEx.findStatementAccount(beginTime, endTime, organId, supType, page);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public int findStatementAccountCount(String beginTime, String endTime, Integer organId, String supType) throws Exception{
        int result = 0;
        try{
            result =depotHeadMapperEx.findStatementAccountCount(beginTime, endTime, organId, supType);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    public BigDecimal findAllMoney(Integer supplierId, String type, String subType, String mode, String endTime)throws Exception {
        String modeName = "";
        BigDecimal allOtherMoney = BigDecimal.ZERO;
        if (mode.equals("实际")) {
            modeName = "change_amount";
        } else if (mode.equals("合计")) {
            modeName = "discount_last_money";
            allOtherMoney = depotHeadMapperEx.findAllOtherMoney(supplierId, type, subType, endTime);
        }
        BigDecimal result = BigDecimal.ZERO;
        try{
            result =depotHeadMapperEx.findAllMoney(supplierId, type, subType, modeName, endTime);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        if(allOtherMoney!=null) {
            result = result.add(allOtherMoney);
        }
        return result;
    }

    /**
     * 统计总金额
     * @param getS
     * @param type
     * @param subType
     * @param mode 合计或者金额
     * @return
     */
    public BigDecimal allMoney(String getS, String type, String subType, String mode, String endTime) {
        BigDecimal allMoney = BigDecimal.ZERO;
        try {
            Integer supplierId = Integer.valueOf(getS);
            BigDecimal sum = findAllMoney(supplierId, type, subType, mode, endTime);
            if(sum != null) {
                allMoney = sum;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回正数，如果负数也转为正数
        if ((allMoney.compareTo(BigDecimal.ZERO))==-1) {
            allMoney = allMoney.abs();
        }
        return allMoney;
    }

    /**
     * 查询单位的累计应收和累计应付，零售不能计入
     * @param supplierId
     * @param endTime
     * @param supType
     * @return
     */
    public BigDecimal findTotalPay(Integer supplierId, String endTime, String supType) {
        BigDecimal sum = BigDecimal.ZERO;
        String getS = supplierId.toString();
        int i = 1;
        if (("customer").equals(supType)) { //客户
            i = 1;
        } else if (("vendor").equals(supType)) { //供应商
            i = -1;
        }
        //进销部分
        sum = sum.subtract((allMoney(getS, "入库", "采购", "合计",endTime).subtract(allMoney(getS, "入库", "采购", "实际",endTime))).multiply(new BigDecimal(i)));
        sum = sum.subtract((allMoney(getS, "入库", "销售退货", "合计",endTime).subtract(allMoney(getS, "入库", "销售退货", "实际",endTime))).multiply(new BigDecimal(i)));
        sum = sum.add((allMoney(getS, "出库", "销售", "合计",endTime).subtract(allMoney(getS, "出库", "销售", "实际",endTime))).multiply(new BigDecimal(i)));
        sum = sum.add((allMoney(getS, "出库", "采购退货", "合计",endTime).subtract(allMoney(getS, "出库", "采购退货", "实际",endTime))).multiply(new BigDecimal(i)));
        return sum;
    }

    public List<DepotHeadVo4List> getDetailByNumber(String number)throws Exception {
        List<DepotHeadVo4List> resList = new ArrayList<DepotHeadVo4List>();
        List<DepotHeadVo4List> list = null;
        try{
            list = depotHeadMapperEx.getDetailByNumber(number);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        if (null != list) {
            for (DepotHeadVo4List dh : list) {
                if(dh.getAccountIdList() != null) {
                    String accountidlistStr = dh.getAccountIdList().replace("[", "").replace("]", "").replaceAll("\"", "");
                    dh.setAccountIdList(accountidlistStr);
                }
                if(dh.getAccountMoneyList() != null) {
                    String accountmoneylistStr = dh.getAccountMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
                    dh.setAccountMoneyList(accountmoneylistStr);
                }
                if(dh.getOtherMoneyList() != null) {
                    String otherMoneyListStr = dh.getOtherMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
                    dh.setOtherMoneyList(otherMoneyListStr);
                }
                if(dh.getOtherMoneyItem() != null) {
                    String otherMoneyItemStr = dh.getOtherMoneyItem().replace("[", "").replace("]", "").replaceAll("\"", "");
                    dh.setOtherMoneyItem(otherMoneyItemStr);
                }
                if(dh.getChangeAmount() != null) {
                    dh.setChangeAmount(dh.getChangeAmount().abs());
                }
                if(dh.getTotalPrice() != null) {
                    dh.setTotalPrice(dh.getTotalPrice().abs());
                }
                dh.setOperTimeStr(dh.getOperTime());
                dh.setMaterialsList(findMaterialsListByHeaderId(dh.getId()));
                resList.add(dh);
            }
        }
        return resList;
    }

    /**
     * 新增单据主表及单据子表信息
     * @param beanJson
     * @param rows
     * @param tenantId
     * @param request
     * @throws Exception
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void addDepotHeadAndDetail(String beanJson, String rows, Long tenantId,
                                      HttpServletRequest request,Long userId) throws Exception {

        /**处理单据主表数据*/
        DepotHead depotHead = JSONObject.parseObject(beanJson, DepotHead.class);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
//        orderMessageSaveEntity.setSendtime(dateFormat.format(date));
       // dateFormat.format(depotHead.getDeliverDate());

        Date date2=new Date();
        Date date3=new Date();
        Date date4=new Date();
        if(depotHead.getDeliverDate()!=null&&!depotHead.getDeliverDate().equals("")){
            date2 = dateFormat.parse(depotHead.getDeliverDate());
        }

        if(depotHead.getSalesDate()!=null&&!depotHead.getSalesDate().equals("")){
            date3 = dateFormat.parse(depotHead.getSalesDate());
        }
        if(depotHead.getExpectedDate()!=null&&!depotHead.getExpectedDate().equals("")){
            date4 = dateFormat.parse(depotHead.getExpectedDate());
        }
        depotHead.setDeliverDate(dateFormat.format(date2));
        depotHead.setSalesDate(dateFormat.format(date3));
        depotHead.setExpectedDate(dateFormat.format(date4));

//        System.out.println(depotHead.getDeliverDate()+"哈哈"+depotHead.getSalesDate());

        depotHead.setCreator(userId);
//        depotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
        depotHead.setStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
        try{
            depotHeadMapper.insertSelective(depotHead);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        /**入库和出库处理预付款信息*/
        if(BusinessConstants.PAY_TYPE_PREPAID.equals(depotHead.getPayType())){
            if(depotHead.getOrganId()!=null) {
                supplierService.updateAdvanceIn(depotHead.getOrganId(), BigDecimal.ZERO.subtract(depotHead.getTotalPrice()));
            }
        }
        //根据单据编号查询单据id
        DepotHeadExample dhExample = new DepotHeadExample();
        dhExample.createCriteria().andDefaultNumberEqualTo(depotHead.getDefaultNumber()).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<DepotHead> list = depotHeadMapper.selectByExample(dhExample);
        if(list!=null) {
            Long headId = list.get(0).getId();
            /**入库和出库处理单据子表信息*/
            depotItemService.saveDetials(rows,headId,tenantId, request,userId);
        }
        /**如果关联单据号非空则更新订单的状态为2 */
        if(depotHead.getLinkNumber()!=null) {
            DepotHead depotHeadOrders = new DepotHead();
            depotHeadOrders.setStatus(BusinessConstants.BILLS_STATUS_SKIP);
            DepotHeadExample example = new DepotHeadExample();
            example.createCriteria().andNumberEqualTo(depotHead.getLinkNumber());
            try{
                depotHeadMapper.updateByExampleSelective(depotHeadOrders, example);
            }catch(Exception e){
                JshException.writeFail(logger, e);
            }
        }

    }


    /**
     * 新增单据主表及单据子表信息   调拨单
     * @param beanJson
     * @param rows
     * @param tenantId
     * @param request
     * @throws Exception
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void addTransferAndDetail(String beanJson, String rows, Long tenantId,
                                      HttpServletRequest request,Long userId) throws Exception {

        /**处理单据主表数据*/
        DepotHead depotHead = JSONObject.parseObject(beanJson, DepotHead.class);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));

        depotHead.setCreator(userId);
//        depotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
        depotHead.setStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
        try{
            depotHeadMapper.insertTransferAndDetail(depotHead);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        /**入库和出库处理预付款信息*/
        if(BusinessConstants.PAY_TYPE_PREPAID.equals(depotHead.getPayType())){
            if(depotHead.getOrganId()!=null) {
                supplierService.updateAdvanceIn(depotHead.getOrganId(), BigDecimal.ZERO.subtract(depotHead.getTotalPrice()));
            }
        }
        //根据单据编号查询单据id
        DepotHeadExample dhExample = new DepotHeadExample();
        dhExample.createCriteria().andDefaultNumberEqualTo(depotHead.getDefaultNumber()).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<DepotHead> list = depotHeadMapper.selectByExample(dhExample);
        if(list!=null) {
            Long headId = list.get(0).getId();
            /**入库和出库处理单据子表信息*/
            depotItemService.saveTransferDetials(rows,headId,tenantId, request,userId);
        }
        /**如果关联单据号非空则更新订单的状态为2 */
        if(depotHead.getLinkNumber()!=null) {
            DepotHead depotHeadOrders = new DepotHead();
            depotHeadOrders.setStatus(BusinessConstants.BILLS_STATUS_SKIP);
            DepotHeadExample example = new DepotHeadExample();
            example.createCriteria().andNumberEqualTo(depotHead.getLinkNumber());
            try{
                depotHeadMapper.updateByExampleSelective(depotHeadOrders, example);
            }catch(Exception e){
                JshException.writeFail(logger, e);
            }
        }

    }




    /**
     * 新增单据主表及单据子表信息   形态转换单
     * @param beanJson
     * @param rows
     * @param tenantId
     * @param request
     * @throws Exception
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void addModalShiftAndDetail(String beanJson, String rows, Long tenantId,
                                     HttpServletRequest request,Long userId) throws Exception {

        /**处理单据主表数据*/
        DepotHead depotHead = JSONObject.parseObject(beanJson, DepotHead.class);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));

        depotHead.setCreator(userId);
//        depotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
        depotHead.setStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
        try{
            depotHeadMapper.insertModalShiftAndDetail(depotHead);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        /**入库和出库处理预付款信息*/
        if(BusinessConstants.PAY_TYPE_PREPAID.equals(depotHead.getPayType())){
            if(depotHead.getOrganId()!=null) {
                supplierService.updateAdvanceIn(depotHead.getOrganId(), BigDecimal.ZERO.subtract(depotHead.getTotalPrice()));
            }
        }
        //根据单据编号查询单据id
        DepotHeadExample dhExample = new DepotHeadExample();
        dhExample.createCriteria().andDefaultNumberEqualTo(depotHead.getDefaultNumber()).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<DepotHead> list = depotHeadMapper.selectByExample(dhExample);
        if(list!=null) {
            Long headId = list.get(0).getId();
            /**入库和出库处理单据子表信息*/
            depotItemService.saveModalShiftAndDetials(rows,headId,tenantId, request,userId);
        }
        /**如果关联单据号非空则更新订单的状态为2 */
        if(depotHead.getLinkNumber()!=null) {
            DepotHead depotHeadOrders = new DepotHead();
            depotHeadOrders.setStatus(BusinessConstants.BILLS_STATUS_SKIP);
            DepotHeadExample example = new DepotHeadExample();
            example.createCriteria().andNumberEqualTo(depotHead.getLinkNumber());
            try{
                depotHeadMapper.updateByExampleSelective(depotHeadOrders, example);
            }catch(Exception e){
                JshException.writeFail(logger, e);
            }
        }

    }




    /**
     * 新增单据主表及单据子表信息   盘点单
     * @param beanJson
     * @param rows
     * @param tenantId
     * @param request
     * @throws Exception
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void addCheckAndDetail(String beanJson, String rows, Long tenantId,
                                       HttpServletRequest request,Long userId) throws Exception {

        /**处理单据主表数据*/
        DepotHead depotHead = JSONObject.parseObject(beanJson, DepotHead.class);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));

        depotHead.setCreator(userId);
//        depotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
        depotHead.setStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
        try{
            depotHeadMapper.insertCheckAndDetail(depotHead);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        /**入库和出库处理预付款信息*/
        if(BusinessConstants.PAY_TYPE_PREPAID.equals(depotHead.getPayType())){
            if(depotHead.getOrganId()!=null) {
                supplierService.updateAdvanceIn(depotHead.getOrganId(), BigDecimal.ZERO.subtract(depotHead.getTotalPrice()));
            }
        }
        //根据单据编号查询单据id
        DepotHeadExample dhExample = new DepotHeadExample();
        dhExample.createCriteria().andDefaultNumberEqualTo(depotHead.getDefaultNumber()).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<DepotHead> list = depotHeadMapper.selectByExample(dhExample);
        if(list!=null) {
            Long headId = list.get(0).getId();
            /**入库和出库处理单据子表信息*/
            depotItemService.saveCheckAndDetials(rows,headId,tenantId, request,userId);
        }
        /**如果关联单据号非空则更新订单的状态为2 */
        if(depotHead.getLinkNumber()!=null) {
            DepotHead depotHeadOrders = new DepotHead();
            depotHeadOrders.setStatus(BusinessConstants.BILLS_STATUS_SKIP);
            DepotHeadExample example = new DepotHeadExample();
            example.createCriteria().andNumberEqualTo(depotHead.getLinkNumber());
            try{
                depotHeadMapper.updateByExampleSelective(depotHeadOrders, example);
            }catch(Exception e){
                JshException.writeFail(logger, e);
            }
        }

    }






    /**
     * 更新单据主表及单据子表信息
     * @param id
     * @param beanJson
     * @param rows
     * @param preTotalPrice
     * @param tenantId
     * @param request
     * @throws Exception
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void updateDepotHeadAndDetail(Long id, String beanJson, String rows,
                                         BigDecimal preTotalPrice, Long tenantId,HttpServletRequest request,Long userId)throws Exception {
        /**更新单据主表信息*/
        DepotHead depotHead = JSONObject.parseObject(beanJson, DepotHead.class);
        //判断用户是否已经登录过，登录过不再处理
        depotHead.setId(id);
        try{
            depotHeadMapper.updateByPrimaryKeySelective(depotHead);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        /**入库和出库处理预付款信息*/
        if(BusinessConstants.PAY_TYPE_PREPAID.equals(depotHead.getPayType())){
            if(depotHead.getOrganId()!=null){
                supplierService.updateAdvanceIn(depotHead.getOrganId(), BigDecimal.ZERO.subtract(depotHead.getTotalPrice().subtract(preTotalPrice)));
            }
        }
        /**入库和出库处理单据子表信息*/
        depotItemService.saveDetials(rows,depotHead.getId(),tenantId,request,userId);

    }


    /**
     * 更新单据主表及单据子表信息  调拨单
     * @param id
     * @param beanJson
     * @param rows
     * @param preTotalPrice
     * @param tenantId
     * @param request
     * @throws Exception
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void updateTransferAndDetail(Long id, String beanJson, String rows,
                                         BigDecimal preTotalPrice, Long tenantId,HttpServletRequest request,Long userId)throws Exception {
        /**更新单据主表信息*/
        DepotHead depotHead = JSONObject.parseObject(beanJson, DepotHead.class);
        //判断用户是否已经登录过，登录过不再处理
        depotHead.setId(id);
        try{
            depotHeadMapper.updateTransferAndDetail(depotHead);

        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        /**入库和出库处理预付款信息*/
        if(BusinessConstants.PAY_TYPE_PREPAID.equals(depotHead.getPayType())){
            if(depotHead.getOrganId()!=null){
                supplierService.updateAdvanceIn(depotHead.getOrganId(), BigDecimal.ZERO.subtract(depotHead.getTotalPrice().subtract(preTotalPrice)));
            }
        }
        /**入库和出库处理单据子表信息*/
        depotItemService.saveTransferDetials(rows,depotHead.getId(),tenantId,request,userId);

    }


    /**
     * 更新单据主表及单据子表信息  形态转换单
     * @param id
     * @param beanJson
     * @param rows
     * @param preTotalPrice
     * @param tenantId
     * @param request
     * @throws Exception
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void updateModalShiftAndDetail(Long id, String beanJson, String rows,
                                        BigDecimal preTotalPrice, Long tenantId,HttpServletRequest request,Long userId)throws Exception {
        /**更新单据主表信息*/
        DepotHead depotHead = JSONObject.parseObject(beanJson, DepotHead.class);
        //判断用户是否已经登录过，登录过不再处理
        depotHead.setId(id);
        try{
            depotHeadMapper.updateTransferAndDetail(depotHead);

        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        /**入库和出库处理预付款信息*/
        if(BusinessConstants.PAY_TYPE_PREPAID.equals(depotHead.getPayType())){
            if(depotHead.getOrganId()!=null){
                supplierService.updateAdvanceIn(depotHead.getOrganId(), BigDecimal.ZERO.subtract(depotHead.getTotalPrice().subtract(preTotalPrice)));
            }
        }
        /**入库和出库处理单据子表信息*/
        depotItemService.saveModalShiftAndDetials(rows,depotHead.getId(),tenantId,request,userId);

    }


    /**
     * 更新单据主表及单据子表信息  盘点单
     * @param id
     * @param beanJson
     * @param rows
     * @param preTotalPrice
     * @param tenantId
     * @param request
     * @throws Exception
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void updateCheckAndDetail(Long id, String beanJson, String rows,
                                          BigDecimal preTotalPrice, Long tenantId,HttpServletRequest request,Long userId)throws Exception {
        /**更新单据主表信息*/
        DepotHead depotHead = JSONObject.parseObject(beanJson, DepotHead.class);
        //判断用户是否已经登录过，登录过不再处理
        depotHead.setId(id);
        try{
            depotHeadMapper.updateTransferAndDetail(depotHead);

        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        /**入库和出库处理预付款信息*/
        if(BusinessConstants.PAY_TYPE_PREPAID.equals(depotHead.getPayType())){
            if(depotHead.getOrganId()!=null){
                supplierService.updateAdvanceIn(depotHead.getOrganId(), BigDecimal.ZERO.subtract(depotHead.getTotalPrice().subtract(preTotalPrice)));
            }
        }
        /**入库和出库处理单据子表信息*/
        depotItemService.saveCheckAndDetials(rows,depotHead.getId(),tenantId,request,userId);

    }

    /**
     * 删除单据主表及子表信息
     * @param id
     * @throws Exception
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void deleteDepotHeadAndDetail(Long id, HttpServletRequest request,Long userId,Long tenantId) throws Exception {
        //查询单据主表信息
        DepotHead depotHead =getDepotHead(id);

        //删除出库数据回收序列号
        if(BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType())
                &&!BusinessConstants.SUB_TYPE_TRANSFER.equals(depotHead.getSubType())){
            //查询单据子表列表
            List<DepotItem> depotItemList=null;
            try{
                depotItemList = depotItemMapperEx.findDepotItemListBydepotheadId(id,BusinessConstants.ENABLE_SERIAL_NUMBER_ENABLED);
            }catch(Exception e){
                JshException.readFail(logger, e);
            }

            /**回收序列号*/
            if(depotItemList!=null&&depotItemList.size()>0){
                for(DepotItem depotItem:depotItemList){
                    //BasicNumber=OperNumber*ratio
                    serialNumberService.cancelSerialNumber(depotItem.getMaterialId(), depotItem.getHeaderId(),(depotItem.getBasicNumber()==null?0:depotItem.getBasicNumber()).intValue(),userId);
                }
            }
        }
        /**删除单据子表数据*/
        try{
            depotItemMapperEx.batchDeleteDepotItemByDepotHeadIds(new Long []{id});
            //更新当前库存
            List<DepotItem> list = depotItemService.getListByHeaderId(id);
            for(DepotItem depotItem: list){

                if(tenantId != null){
                    depotItemService.updateCurrentStock(depotItem,tenantId);
                }
            }
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }

        /**删除单据主表信息*/
        batchDeleteDepotHeadByIds(id.toString(),userId);
    }

    /**
     * 批量删除单据主表及子表信息
     * @param ids
     * @throws Exception
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void batchDeleteDepotHeadAndDetail(String ids, HttpServletRequest request,Long userId,Long tenantId) throws Exception{
        if(StringUtil.isNotEmpty(ids)){
            String [] headIds=ids.split(",");
            for(int i=0;i<headIds.length;i++){
                deleteDepotHeadAndDetail(Long.valueOf(headIds[i]), request,userId,tenantId);
            }
        }
    }
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteDepotHeadByIds(String ids,Long userId)throws Exception {

        String [] idArray=ids.split(",");
        int result=0;
        try{
            result = depotHeadMapperEx.batchDeleteDepotHeadByIds(new Date(),userId,idArray);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    public BigDecimal getBuyAndSaleStatistics(String type, String subType, Integer hasSupplier, String beginTime, String endTime) {
        return depotHeadMapperEx.getBuyAndSaleStatistics(type, subType, hasSupplier, beginTime, endTime);
    }

    public BigDecimal getBuyAndSaleRetailStatistics(String type, String subType, Integer hasSupplier, String beginTime, String endTime) {
        return depotHeadMapperEx.getBuyAndSaleRetailStatistics(type, subType, hasSupplier, beginTime, endTime);
    }




    public PageUtils selectOrderProduct(int currPage, int pageSize,String createTime,String orderSn,String memberUsername,String receiverName,String receiverPhone,String status,String isOrderNumber)throws Exception {
        List<SellOrder> resList = new ArrayList<SellOrder>();
        String begin="";
        String end="";
        if(createTime==null){
        }else{
            begin= createTime+" 00:00:00";
            end=createTime+" 24:00:00";
        }


        Page<SellOrder> page = new Page<>(currPage,pageSize);
        try{
//            String [] creatorArray = getCreatorArray(roleType,userId);
            page.setRecords(depotHeadMapperEx.selectOrderProduct(page,begin,end,orderSn,memberUsername,receiverName,receiverPhone,status,isOrderNumber));
        }catch(Exception e){
            JshException.readFail(logger, e);
        }

        return new PageUtils(page);
    }


    public PageUtils selectReturnOrderProduct(int currPage, int pageSize,String createTime,String orderSn,String serviceNumber,String memberCompany,String receiveMan,String status,String type,String isReturnNumber,String receivePhone)throws Exception {
        List<ReturnOrder> resList = new ArrayList<ReturnOrder>();

        Page<ReturnOrder> page = new Page<>(currPage,pageSize);
        try{
            page.setRecords(depotHeadMapperEx.selectReturnOrderProduct(page,createTime,orderSn,serviceNumber,memberCompany,receiveMan,status,type,isReturnNumber,receivePhone));
        }catch(Exception e){
            JshException.readFail(logger, e);
        }

        return new PageUtils(page);
    }


//    public PageUtils selectByOrderSn(int currPage, int pageSize,String orderSn)throws Exception {
//        List<ProductInfo> resList = new ArrayList<ProductInfo>();
//
//        Page<ProductInfo> page = new Page<>(currPage,pageSize);
//        try{
////            String [] creatorArray = getCreatorArray(roleType,userId);
//            page.setRecords(depotHeadMapperEx.selectByOrderSn(page,orderSn));
//        }catch(Exception e){
//            JshException.readFail(logger, e);
//        }
//
//        return new PageUtils(page);
//    }


    public PageUtils selectByOrderSn(int currPage, int pageSize,String orderSn)throws Exception {
        List<ProductInfo> resList = new ArrayList<ProductInfo>();

        Page<ProductExtendVo> page = new Page<>(currPage,pageSize);
        try{
//            String [] creatorArray = getCreatorArray(roleType,userId);
            page.setRecords(depotHeadMapperEx.selectByOrderSn(page,orderSn));
        }catch(Exception e){
            JshException.readFail(logger, e);
        }

        return new PageUtils(page);
    }


    public PageUtils selectByServiceNumber(int currPage, int pageSize,String serviceNumber)throws Exception {
        List<ReturnProduct> resList = new ArrayList<ReturnProduct>();

        Page<ReturnProduct> page = new Page<>(currPage,pageSize);
        try{
//            String [] creatorArray = getCreatorArray(roleType,userId);
            page.setRecords(depotHeadMapperEx.selectByServiceNumber(page,serviceNumber));
        }catch(Exception e){
            JshException.readFail(logger, e);
        }

        return new PageUtils(page);
    }




}
